import { t } from 'i18next'
import React, { useState } from 'react'
import { Button, Modal } from '@kedacom/react-next'
import copy from 'copy-to-clipboard'
import {
	ShareViewStyle,
	FormWrapStyle,
	FormItemStyle,
	FormTitleStyle,
	FormContentStyle,
	FuncStyle,
	ErrorStyle,
	MaskContainerStyle,
} from './style'
import { useData } from './hooks'
import { Environment, getMeetingTime } from '@/utils'
import wechatPng from '@img/wechat_mini_apps_movision.jpg'
import { fetchSetCookieForShare } from '@/api/share'

export default function ShareView({ meetingMoid }: { meetingMoid: string }) {
	const { shareInfo, errorMsg, loaded } = useData(meetingMoid)
	const [wxWorkText, setWxWorkText] = useState(t('客户端入会'))
	const [showMask, setShowMask] = useState(false)
	const onCopy = (text: string) => {
		copy(text)
		const m = Modal.alert({
			title: t('提示'),
			width: Environment.isMobile ? '90%' : 400,
			height: Environment.isMobile ? '200px' : 260,
			onOk: () => {
				m.hide()
			},
			onCancel: () => {
				m.hide()
			},
			content: <div>{t('复制成功')}</div>,
			okText: t('确定'),
			cancelText: '',
		})
	}
	const openAppByIframe = (openUrl: string) => {
		let ifr = document.createElement('iframe')
		ifr.src = openUrl
		ifr.style.display = 'none'
		document.body.appendChild(ifr)
	}
	let mobileLink = shareInfo.e164
		? `truelink://truelink.kedacom.com?confName=${shareInfo.subject}&confId=${shareInfo.e164}&isAnonymous=${shareInfo.allowAnonymousMt}`
		: ''
	if (Environment.isIOS) {
		mobileLink = shareInfo.e164
			? `KedacomSky://isJoinMeeting=1&meetingId=${shareInfo.e164}&meetingName=${shareInfo.subject}&isAnonymous=${shareInfo.allowAnonymousMt}`
			: ''
	}
	const pcRender = () => {
		const downloadUrl = '/portal/downloadCore.html'
		// window的拉起暂不支持，年后
		let pcLink = shareInfo.e164 ? `win` : ''
		if (Environment.isMac) {
			pcLink = shareInfo.e164
				? `KedacomSkyMac://isJoinMeeting=1&meetingId=${shareInfo.e164}&meetingName=${shareInfo.subject}&isAnonymous=${shareInfo.allowAnonymousMt}`
				: ''
			// downloadUrl = 'https://www.kedacom.com/cn/r/cms/www/download/2021/Kedacom_SKY.dmg'
		}
		const browserMeeting = async () => {
			const res = await fetchSetCookieForShare(shareInfo.meetingMoid).catch((response) => {
				if (response) {
					const { data } = response
					if (
						data &&
						((data.errorCode &&
							(data.errorCode === 100013 ||
								data.errorCode === 100012 ||
								data.errorCode === 100011 ||
								data.errorCode === 100010)) ||
							(data.error_code &&
								(data.error_code === 100013 ||
									data.error_code === 100012 ||
									data.error_code === 100011 ||
									data.error_code === 100010)))
					) {
						window.open(
							`${window.origin}/portal/login?jump=${btoa(
								JSON.stringify({
									from: window.location.href,
									to: `${window.origin}/skyforweb/?roomId=${shareInfo.e164}`,
									e: `${shareInfo.e164}`,
								})
							)}`,
							'_blank'
						)
						return 'noLogin'
					}
				}
			})
			if (res !== 'noLogin') {
				if (res && res.success && res.data) {
					try {
						var meeting_machine_link = localStorage.getItem('meeting_machine_link') as any
						if (meeting_machine_link) {
							meeting_machine_link = JSON.parse(meeting_machine_link)
						} else {
							meeting_machine_link = {
								list: {}, //会议与机房的关联表
								meeting_machine_moid: '', //存储当前最新机房的moid
							}
						}
						var meeting_machine_moid = res.data
						meeting_machine_link.list[shareInfo.meetingMoid] = meeting_machine_moid
						meeting_machine_link.meeting_machine_moid = meeting_machine_moid
						localStorage.setItem('meeting_machine_link', JSON.stringify(meeting_machine_link))
					} catch (e) {
						console.error(t('存储会议、机房关系报错'), e)
					}
				}
				window.open(`${window.origin}/skyforweb/?roomId=${shareInfo.e164}`, '_blank')
			}
		}
		return (
			<>
				{shareInfo.enableRtc === 1 && (
					<Button
						width={116}
						onClick={() => {
							browserMeeting()
						}}
					>
						{t('浏览器入会')}
					</Button>
				)}
				{pcLink.length > 0 && (
					<Button width={116} onClick={() => openAppByIframe(pcLink)}>
						{t('客户端入会')}
					</Button>
				)}
				<div className="enter_tips">
					{t('如未安装客户端，请先')}
					<a className="download" href={downloadUrl}>
						{t('下载客户端')}
					</a>
				</div>
			</>
		)
	}
	const mobileRender = () => {
		let downloadUrl = '/portal/downloadCore.html'
		let isDownload = false
		if (Environment.isIOS) {
			downloadUrl = 'https://apps.apple.com/cn/app/id1549831957'
			isDownload = true
		}
		return (
			<>
				{Environment.isInWeiXin ? (
					<Button
						width={116}
						onClick={(e) => {
							setWxWorkText(t('客户端入会'))
							setShowMask(true)
						}}
					>
						{t('客户端入会')}
					</Button>
				) : (
					<a href={mobileLink}>
						<Button width={116}>{t('客户端入会')}</Button>
					</a>
				)}
				<div className="enter_tips">
					{t('如未安装客户端，请先')}
					{isDownload ? (
						Environment.isWeiXinWork ? (
							<span
								className="download"
								onClick={(e) => {
									setWxWorkText(t('下载客户端'))
									setShowMask(true)
								}}
							>
								{t('下载客户端')}
							</span>
						) : (
							<a className="download" href={downloadUrl} download>
								{t('下载客户端')}
							</a>
						)
					) : (
						<a className="download" href={downloadUrl}>
							{t('下载客户端')}
						</a>
					)}
				</div>
			</>
		)
	}
	return (
		<>
			{shareInfo.e164 && Environment.isInWeiXin && showMask && (
				<MaskContainerStyle className="mask-container">
					<div className="mask" onClick={() => setShowMask(false)}></div>
					<div className="top-tips"></div>
					<div className="top-tips-message">
						<p>
							{Environment.isMobile && Environment.isWeiXinWork ? `"${wxWorkText}"` : t('客户端入会')}
							{t('请在右上角"更多"')}
						</p>
						<p style={{ marginLeft: '6px' }}>{t('按钮中选择在浏览器中打开。')}</p>
					</div>
				</MaskContainerStyle>
			)}
			{shareInfo.e164 && (
				<ShareViewStyle>
					<div className="top_title">{t('入会方式选择')}</div>
					<FormWrapStyle>
						<FormItemStyle>
							<FormTitleStyle>{t('会议名称')}</FormTitleStyle>
							<FormContentStyle>{shareInfo.subject}</FormContentStyle>
						</FormItemStyle>
						{shareInfo.startTime && (
							<FormItemStyle>
								<FormTitleStyle>{t('会议时间')}</FormTitleStyle>
								<FormContentStyle>
									<div>
										{getMeetingTime(
											shareInfo.startTime,
											shareInfo.duration,
											shareInfo.duration === 0
										)}
									</div>
								</FormContentStyle>
							</FormItemStyle>
						)}
						<FormItemStyle>
							<FormTitleStyle>{t('会议号码')}</FormTitleStyle>
							<FormContentStyle>
								<span>{shareInfo.e164}</span>
								<i className="copy" onClick={() => onCopy(shareInfo.e164)}></i>
							</FormContentStyle>
						</FormItemStyle>
					</FormWrapStyle>
					<FuncStyle>
						{!Environment.isMobile && pcRender()}
						{Environment.isMobile && mobileRender()}
						{shareInfo.enableWechat === 1 && (
							<>
								<img src={wechatPng} alt={''} />
								<div className="enter_tips">{t('使用微信扫描或识别二维码加入会议')}</div>
							</>
						)}
					</FuncStyle>
				</ShareViewStyle>
			)}
			{loaded && (shareInfo == null || !shareInfo.e164) && (
				<ErrorStyle>
					<div className="err_icon_line">
						<div className="err_icon"></div>
					</div>
					<div className="err_msg">{errorMsg}</div>
				</ErrorStyle>
			)}
		</>
	)
}
